from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request
from flask import session

from info import constants
from info import db
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import profile_blu
from flask import render_template


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    # 显示的是所有我发送的新闻
    user = g.user
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news_dict in items:
        news_dict_li.append(news_dict.to_review_dict())
    data = {
        'news_list':news_dict_li,
        'current_page':current_page,
        'total_page':total_page,
    }

    return render_template('/news/user_news_list.html',data=data)


@profile_blu.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        categories_list = []
        for category in categories:
            categories_list.append(category.to_dict())
        categories_list.pop(0)
        data = {
            'categories':categories_list,
        }

        return render_template('news/user_news_release.html',data=data)
    else:
        title = request.form.get('title')
        category_id = request.form.get('category_id')
        digest = request.form.get('digest')
        # TODO 等待七牛云
        # index_image = request.files.get('index_image')
        content = request.form.get('content')
        source = "个人发布"
        if not all([title, source, digest, content, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
#         将图片上传到七牛
        news = News()
        news.title = title
        news.digest = digest
        news.source = source
        news.content = content
        # news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.user_id = g.user.id
        news.status = 1
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        # 5. 返回结果
        return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")

@profile_blu.route('/pic_info',methods = ['GET','POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method =='GET':
        return render_template('news/user_pic_info.html')



@profile_blu.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登录')
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    collections = []
    current_page = 1
    total_page = 1
    # 分页查询
    try:
        paginate=user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

        # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())
    data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}
    return render_template('news/user_collection.html',data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    else:
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')
        if not all([old_password,new_password]):
            return jsonify(errno=RET.PARAMERR,errmsg='参数不足')
    #     查询出这个人的密码,与原密码判断
        if not user.check_password(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    #     如果正确,那么把密码改为新密码,保存到数据库
        user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

        return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/base_info',methods=['GET','POST'])
@user_login_data
def base_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_base_info.html',data={"user_info": user.to_dict()})
#     如果不是get,那么就会执行下面的操作
    else:
        data_dict = request.json
        nick_name = data_dict.get("nick_name")
        gender = data_dict.get("gender")
        signature = data_dict.get("signature")
        if not all([nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        if gender not in (['MAN', 'WOMAN']):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        # 3. 更新并保存数据
        user.nick_name = nick_name
        user.gender = gender
        user.signature = signature
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

        # 将 session 中保存的数据进行实时更新
        session["nick_name"] = nick_name

        # 4. 返回响应
        return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route('/info')
@user_login_data
def get_user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {'user_info':user.to_dict() }
    return render_template('news/user.html',data=data)